const jwt = require('jsonwebtoken');

const intercept = (app) => {
    app.all('*', (req, res, next) => {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
        res.header('Access-Control-Allow-Methods', '*');
        res.header('Content-Type', 'application/json;charset=utf-8');
        //跨域请求
        isToken(req, res, next);
    })
}
//全局拦截


const isToken = (req, res, next) => {
    if (req.path != '/rear/login' && req.path.substr(1, 4) === 'rear') {
        let token = req.get("Authorization");
        let secretOrPrivateKey = "jwt";
        jwt.verify(token, secretOrPrivateKey, err => {
            if (err) {
                res.json({
                    status: 0,
                    message: '缺少tokan'
                })
            } else {
                isJuris(req, res, next, token);
            }
        })
    } else {
        next();
    }
}
//判断token

const isJuris = (req, res, next, token) => {
    let juris = JSON.stringify(jwt.decode(token).juris);
    let url = req.url;
    if(juris.indexOf(url.split('?')[0]) > -1) {
        next();
    } else {
        res.json({
            status: 403,
            message: '没有权限'
        })
    }
}

module.exports = intercept